using AuthClientApi.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;

namespace AuthClientApi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]/[Action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly OpenidConfiguration _openidConfiguration;
        private readonly IMemoryCache _memoryCache;

        public WeatherForecastController(
            ILogger<WeatherForecastController> logger,IMemoryCache memoryCache, OpenidConfiguration openidConfiguration)
        {
            _logger = logger;
            _memoryCache = memoryCache;
            _openidConfiguration = openidConfiguration;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet(Name= "GetMyUserInfo")]
        public async Task<object> GetMyUserInfo()
        {
            var id_token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var token=_memoryCache.Get<Rootobject>($"OAuthToken_{id_token.GetHashCode()}");
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Authorization",$"Bearer {token.access_token}"}
            };
            var res=await HttpHelper.GetAsync(_openidConfiguration.userinfo_endpoint, headers);
            return res;
        }
    }
}